import { defineStore } from 'pinia'
import useUserTokenStore from "./token";
import useUserMenuStore from "./menu";

// 用户信息存储
const useUserInfoStore = defineStore("userInfo", {

    state: () =>{
        return {
            userInfo:null,
            homePage:'/'
        }
    },

    actions: {

        // 设置用户token , 后续动态路由也在此处理 return true 之后执行跳转
        async setUserInfo(data) {

            // 获取定制的 token store 实例
            const tokenStore = useUserTokenStore()

            // 获取定制的 menu store 实例
            const menuStore = useUserMenuStore()

            let response =  await $HTTP.post($Server.common.login , data).then(res=> res.Data)

            this.userInfo = response

            // 设置token
            tokenStore.setToken(response.Token)

            // 设置路由权限 ， 同时返回权限主页
            const userMenus = response.BS_UserMenus.filter(item=> item.SystemCode === processEnv.VITE_SYSTEM_CODE )

            let homeIndex = await menuStore.setMenu(userMenus).then(res=>res)

            this.homePage = processEnv.VITE_HOME ||  homeIndex

            // 假装获取到了设定的主页
            return { path: this.homePage  }
            // this.userInfo = data
        },

        // 清除user info
        clearUserInfo(){

            const tokenStore = useUserTokenStore()
            const menuStore = useUserMenuStore()

            // 设置token
            tokenStore.setToken('')
            menuStore.setMenu(null)

            this.$reset()

        }
    },
    persist: {
        enabled: true,
        storage: sessionStorage,
    }
})

export default useUserInfoStore